<template>
  <div class="content-container">
    <el-dialog v-dialogDrag :visible.sync="dialogVisible" class="workReport" title="点检" width="1000px" top="9vh" @close="closeFun()">
      <button-group ref="buttonGroup" @submitForm="submitForm('ruleForm')" @cancel="dialogVisible = false" />
      <div class="formTopFont">设备点检单</div>
      <el-row class="topInfo">
        <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" size="mini">
          <el-row>
            <el-col :span="8">
              <el-form-item prop="pointNo" label="单据号">
                <el-input v-model="ruleForm.pointNo" maxlength="20" show-word-limit />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="checkBy" label="点检人">
                <el-select v-model="ruleForm.checkBy" filterable @change="ruleForm.checkUserName = userInfo.find(item => item.id === ruleForm.checkBy).name">
                  <el-option v-for="item in userInfo" :key="item.id" :value="item.id" :label="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="checkTime" label="点检时间">
                <el-date-picker v-model="ruleForm.checkTime" style="width: 100%" :clearable="false" type="datetime" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <!-- 点检说明 -->
              <el-form-item label="点检说明">
                <el-input v-model="ruleForm.checkInstructions" type="textarea" rows="4" show-word-limit maxlength="500" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="result" label="点检结果">
                <el-checkbox v-model="result" :disabled="isDisabled" :true-label="1" :false-label="0">通过</el-checkbox>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-row>
      <el-table ref="tableData" :data="ruleForm.itemList" border stripe height="300px">
        <el-table-column show-overflow-tooltip label="点检项" min-width="130px">
          <template #default="{ row }">{{ row.itemName }}{{ row.itemCode ? '【' + row.itemCode + '】' : '' }}</template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="itemRemark" label="点检描述" min-width="150px" />
        <el-table-column width="110px" align="center">
          <template slot="header" slot-scope="scope">
            <el-checkbox v-model="isCheck">点检结果</el-checkbox>
          </template>
          <template #default="{ row }">
            <el-checkbox v-model="row.itemResult" :true-label="1" :false-label="0">通过</el-checkbox>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="备注" width="200px" prop="remark">
          <template #default="{ row }">
            <el-input v-model="row.remark" size="small" class="inputHeight" maxlength="1000" show-word-limit />
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer">
        <el-button size="mini" @click="submitForm('ruleForm')">提交</el-button>
        <el-button size="mini" type="primary" @click="dialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { timeFormatToString } from '@/utils/function'
export default {
  components: {},
  props: {
    userInfo: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  computed: {
    isCheck: {
      get() {
        return this.ruleForm.itemList.every((item) => item.itemResult === 1)
      },
      set(val) {
        this.ruleForm.itemList.forEach(
          (item) => (item.itemResult = val ? 1 : 0)
        )
      }
    }
  },
  data() {
    const checkPointNo = async (rule, value, callback) => {
      const res = await this.$axios.get(
        `/equip/point/check/verifyNoUnique?pointNo=${value}&id=${
          this.ruleForm.id || ''
        }`
      )
      if (res?.data.code === 200) {
        return res.data.data ? callback() : new Error(callback('单据号重复！'))
      } else {
        return new Error(callback(res.data.msg))
      }
    }
    return {
      title: '',
      ruleForm: {
        pointNo: '',
        checkBy: '',
        checkUserName: '',
        checkTime: '',
        result: '',
        checkInstructions: '',
        id: '',
        itemList: []
      },
      rules: {
        pointNo: [
          { required: true, message: '单据号不能为空！', trigger: 'blur' },
          { validator: checkPointNo, trigger: 'blur' }
        ],
        checkBy: [
          { required: true, message: '请选择点检人', trigger: 'change' }
        ],
        checkTime: [
          { required: true, message: '请选择点检时间', trigger: 'change' }
        ],
        result: [{ required: false }],
        checkInstructions: [{ required: false }]
      },
      dialogVisible: false,
      userList: [],
      applicantData: [],
      submitLoading: false,
      rows: {},
      isDisabled: false,
      result: ''
    }
  },
  watch: {
    dialogVisible(val) {
      if (val) {
        this.ruleForm.checkTime = timeFormatToString(new Date())
      }
    },
    ruleForm: {
      deep: true,
      handler(row) {
        const list = []
        if (row.itemList) {
          row.itemList.forEach((item) => {
            list.push(item)
          })
          const judge = list.every((item) => item.itemResult === 1)
          if (judge === true) {
            this.result = 1
            this.isDisabled = true
          } else {
            this.result = 0
            this.isDisabled = false
          }
        }
      }
    }
  },
  mounted() {},
  methods: {
    /**
     * @description: 打开弹窗
     * @param {*} row
     * @return {*}
     */
    showDialog(row) {
      this.rows = row
      this.getItemList(row.id)
    },
    /**
     * @description: 获取点检项
     */
    async getItemList(id) {
      const loading = this.$loading({
        lock: true,
        text: '数据加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const res = await this.$axios.get(`/equip/point/check/getCheckItem/${id}`)
      if (res?.data.code === 200) {
        if (res.data.data.length < 1) {
          this.$alert('请维护点检项！', '提示', {
            confirmButtonText: '确认',
            type: 'warning'
          })
          loading.close()
          return
        }
        res.data.data.forEach((item) => {
          item.itemResult = 1
        })
        const obj = {
          itemList: res.data.data
        }
        this.ruleForm = { ...this.ruleForm, ...obj }
        loading.close()
        this.dialogVisible = true
      }
    },
    /** 提交*/
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (
            this.ruleForm.itemList.every((item) => item.itemResult === 1) ===
            false
          ) {
            this.$confirm('存在漏检项，是否确认提交？', '提示', {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning'
            })
              .then(async () => {
                this.saveApi()
              })
              .catch(() => {})
          } else {
            this.saveApi()
          }
        }
      })
    },
    async saveApi(num) {
      this.ruleForm.equipName = this.rows.equipName
      this.ruleForm.equipCode = this.rows.equipCode
      this.ruleForm.id = this.rows.id
      this.ruleForm.result = this.result
      this.$axios
        .post('/equip/point/check/point/check', this.ruleForm)
        .then((res) => {
          if (res && res.data.code === 200) {
            this.$message.success('提交成功！')
            this.$emit('getTableInfo')
            this.resetForm('ruleForm')
            this.dialogVisible = false
          }
        })
    },
    /* 保存转维修关闭事件 */
    closeFun() {
      this.dialogVisible = false
      this.$emit('getTableInfo')
      this.resetForm('ruleForm')
    },
    /**
     * @description: 重置表单校验
     * @param {*} formName
     * @return {*}
     */
    resetForm(formName) {
      this.ruleForm = Object.assign({}, this.$options.data.call(this).ruleForm)
      this.$refs[formName].resetFields()
    }
  }
}
</script>
<style lang="scss">
.workReport {
  .el-dialog__body {
    padding: 10px 20px;
    height: calc(100% - 120px);
  }
}
.inputHeight {
  input {
    height: 25px !important;
  }
}
</style>
<style lang='scss' scoped>
.topInfo {
  height: 160px;
}
.leftOrRight {
  overflow: hidden;
  height: calc(100% - 180px);
  .leftBox {
    width: 200px;
    float: left;
    height: 100%;
    margin-right: 5px;
    h1 {
      font-size: 14px;
      margin: 0;
      padding: 10px 0 10px 15px;
      cursor: pointer;
      background: #eee;
    }
    ul {
      list-style: none;
      padding: 0;
      margin: 0;
      height: 100%;
      overflow-y: auto;
      li {
        height: 35px;
        line-height: 35px;
        padding-left: 15px;
        cursor: pointer;
      }
    }
  }
  .rightBox {
    width: calc(100% - 205px);
    float: left;
    height: 100%;
    h1 {
      font-size: 14px;
      margin: 0;
      padding: 10px 0 10px 15px;
      cursor: pointer;
      background: #eee;
    }
  }
}
</style>
